import { defineStore } from 'pinia';
import { v4 as uuidv4 } from 'uuid';
import type { BlogPost, Tag } from '@/types';

export const useBlogStore = defineStore('blog', {
  state: () => ({
    posts: [] as BlogPost[],
    tags: [] as Tag[],
    editorType: 'markdown' as 'markdown' | 'richtext',
  }),
  
  getters: {
    getPostById: (state) => (id: string) => {
      return state.posts.find(post => post.id === id);
    },
    
    getPublishedPosts: (state) => {
      return state.posts
        .filter(post => post.isPublished)
        .sort((a, b) => new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime());
    },
    
    getAllPosts: (state) => {
      return state.posts.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
    },
    
    getPostsByTag: (state) => (tagId: string) => {
      return state.posts
        .filter(post => post.tags.includes(tagId))
        .sort((a, b) => new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime());
    },
    
    getTagById: (state) => (id: string) => {
      return state.tags.find(tag => tag.id === id);
    },
  },
  
  actions: {
    addPost(post: Partial<BlogPost>) {
      const now = new Date().toISOString();
      const newPost: BlogPost = {
        id: uuidv4(),
        title: post.title || 'Untitled',
        content: post.content || '',
        excerpt: post.excerpt || '',
        publishedAt: post.isPublished ? now : '',
        updatedAt: now,
        tags: post.tags || [],
        coverImage: post.coverImage,
        isPublished: post.isPublished || false,
        author: post.author || 'Anonymous',
      };
      
      this.posts.push(newPost);
      return newPost.id;
    },
    
    updatePost(id: string, post: Partial<BlogPost>) {
      const index = this.posts.findIndex(p => p.id === id);
      if (index !== -1) {
        const now = new Date().toISOString();
        const updatedPost = {
          ...this.posts[index],
          ...post,
          updatedAt: now,
          publishedAt: post.isPublished && !this.posts[index].isPublished 
            ? now 
            : this.posts[index].publishedAt,
        };
        
        this.posts[index] = updatedPost;
        return true;
      }
      return false;
    },
    
    deletePost(id: string) {
      const index = this.posts.findIndex(p => p.id === id);
      if (index !== -1) {
        this.posts.splice(index, 1);
        return true;
      }
      return false;
    },
    
    addTag(tag: Partial<Tag>) {
      const newTag: Tag = {
        id: uuidv4(),
        name: tag.name || 'Untitled',
        slug: tag.slug || tag.name?.toLowerCase().replace(/\s+/g, '-') || 'untitled',
      };
      
      this.tags.push(newTag);
      return newTag.id;
    },
    
    updateTag(id: string, tag: Partial<Tag>) {
      const index = this.tags.findIndex(t => t.id === id);
      if (index !== -1) {
        this.tags[index] = { ...this.tags[index], ...tag };
        return true;
      }
      return false;
    },
    
    deleteTag(id: string) {
      const index = this.tags.findIndex(t => t.id === id);
      if (index !== -1) {
        this.tags.splice(index, 1);
        // 从所有文章中移除此标签
        this.posts.forEach(post => {
          const tagIndex = post.tags.indexOf(id);
          if (tagIndex !== -1) {
            post.tags.splice(tagIndex, 1);
          }
        });
        return true;
      }
      return false;
    },
    
    setEditorType(type: 'markdown' | 'richtext') {
      this.editorType = type;
    },
    
    exportData() {
      return {
        posts: this.posts,
        tags: this.tags,
      };
    },
    
    importData(data: { posts: BlogPost[], tags: Tag[] }) {
      this.posts = data.posts;
      this.tags = data.tags;
    },
    
    importPosts(posts: BlogPost[]) {
      posts.forEach(post => {
        // 检查文章是否已存在
        const existingIndex = this.posts.findIndex(p => p.id === post.id);
        if (existingIndex === -1) {
          this.posts.push(post);
        } else {
          // 更新现有文章
          this.posts[existingIndex] = post;
        }
      });
    }
  },
  
  persist: true,
}); 